package com.dp.temp;


import com.dp.io.ESN;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @Author LLF
 * @Date Created in 2022/3/26 14:30
 * @Description
 * @Version 2.0
 **/

@Component
@EnableAsync
public class HdTimeChangeTake {


    @Autowired
    JdbcTemplate jdbcTemplate;

    @Autowired
    RedisTemplate redisTemplate;



    //查询计划
    @Async
    public List<Map<String, Object>> plan(String types, LocalDate today) {
        String dateEtime = today.plusDays(1).toString() + " 00:00:00";

        String sql = " SELECT * from (SELECT id, UNAMELIST,UID,UPDATE_DATE, HECK_CYCL, DATE_ADD( UPDATE_DATE, INTERVAL HECK_CYCL ";
        //查出某天要下发哪些任务
        switch (types){
            case "小时":
                sql += " hour) iftime FROM hd_check_plain WHERE DELETED = '0' AND CHECK_CYCLE_UNIT = '小时' ";
                break;
            case "天":
                sql += " day) iftime FROM hd_check_plain WHERE DELETED = '0' AND CHECK_CYCLE_UNIT = '天' ";
                break;
            case "月":
                sql += " month) iftime FROM hd_check_plain WHERE DELETED = '0' AND CHECK_CYCLE_UNIT = '月' ";
                break;
            case "年":
                sql += " year) iftime FROM hd_check_plain WHERE DELETED = '0' AND CHECK_CYCLE_UNIT = '年' ";
                break;
        }
        sql += " AND IFSTAR = '0' AND HECK_CYCL != 0 ) aa where aa.iftime < '"+ dateEtime +"' ";
        List<Map<String, Object>> planList = jdbcTemplate.queryForList(sql);
        return planList;
    }





    /*
    * 查值班排班，请假的人用替班人、替班人上下班时间代替
    * 要求的时间-要上下班开始或结束时间在要求的时间段里
    * 要求的时间段：默认前一天23：50分的时候缓存统计出后一天的所有任务
    * 修改计划触发的缓存，时间段是当天的剩下时间
    * */
    @Async
    public List<Map<String, Object>> onduty(LocalDate today) {

        String dateStime = today.toString() + " 00:00:00";
        String dateEtime = today.plusDays(1).toString() + " 00:00:00";

        //查出来，在日期内上班的人信息
        List<Map<String, Object>> ondutyList = jdbcTemplate.queryForList(" " +
                " SELECT onduty.*, a.nickname, c.job_name, e.dep_name " +
                " FROM ( " +
                "   SELECT a.id, a.mid, a.createtime, " +
                "       IF( a.STATUS = '1', b.did, a.mpeopleid ) mpeopleid, " +
                "       IF( a.STATUS = '1', b.ostime, a.startTime ) startTime, " +
                "       IF( a.STATUS = '1', b.oetime, a.endTime ) endTime" +
                "   FROM" +
                "       onduty_schedule a" +
                "       LEFT JOIN onduty_schedule_out b ON a.id = b.sid " +
                "   WHERE " +
                "       isdelete = '0' " +
                "       AND now() < a.endTime " +
                "       AND a.startTime < '"+ dateEtime +"' " +
                "       AND a.endTime > '"+ dateStime +"'  " +
                "      ) onduty " +
                " LEFT JOIN sys_user a ON a.id = onduty.mpeopleid " +
                " LEFT JOIN sys_jobs_user b ON onduty.mpeopleid = b.user_id " +
                " LEFT JOIN sys_jobs c ON c.job_id = b.job_id " +
                " LEFT JOIN sys_department_user d ON d.user_id = onduty.mpeopleid " +
                " LEFT JOIN sys_department e ON e.dep_id = d.dep_id ");
        System.out.println(dateStime+"==="+dateEtime);
        return ondutyList;
    }





    //默认前一天23：50缓存下一天全部任务
    @Async
//    @Scheduled(cron = "0 30 23 * *  ?")
//    @PostConstruct
    public void hdPlan() throws Exception {
        //先删新表数据，再执行下面代码
        System.out.println(new Date());
//        LocalDate today = LocalDate.now();//今天-切换注释
        LocalDate today = LocalDate.now().plusDays(1);//明天-切换注释
        List<Map<String, Object>> ondutyList = onduty(today);//===========================================================1
        List<Map<String, Object>> planList1 = plan( "小时",today);//生成每日应下发小时任务
        List<Map<String, Object>> planList2 = plan( "天",today);//生成
        List<Map<String, Object>> planList3 = plan( "月",today);//生成
        List<Map<String, Object>> planList4 = plan( "年",today);//生成
        setDeleteNewTasknum();
        if(ondutyList.size()>0 && planList1.size()>0){
            setHourTake(ondutyList,planList1);
        }
        if(planList2.size()>0){
            setNewDayTakeToTable(planList2,Calendar.DAY_OF_YEAR,"天");
        }
        if(planList3.size()>0){
            setNewDayTakeToTable(planList3,Calendar.MONTH,"月");
        }
        if(planList4.size()>0){
            setNewDayTakeToTable(planList4,Calendar.YEAR,"年");
        }
        System.out.println(new Date());
    }

    public void setDeleteNewTasknum(){
        String sql = " TRUNCATE TABLE hd_check_task_new ";
        jdbcTemplate.update(sql);
    }
    public List<Map<String, Object>> finddepjob(Map<String, Object> map){
        String sql = "select e.id,e.nickname,a.dep_name,c.job_name " +
                "FROM sys_department a  " +
                "LEFT JOIN sys_department_jobs b on b.dep_id=a.dep_id " +
                "LEFT JOIN sys_jobs c on c.job_id=b.job_id " +
                "LEFT JOIN sys_jobs_user d on d.job_id = c.job_id " +
                "LEFT JOIN sys_user e on e.id=d.user_id " +
                "where e.id in ('"+map.get("UID").toString().replaceAll(",","','")+"')";
        return jdbcTemplate.queryForList(sql);
    }


    public void setNewDayTakeToTable(List<Map<String,Object>> planList2,int dateType,String timeType){
        List<Map<String, Object>> list = new ArrayList<>();
        for(Map<String,Object> map : planList2){
            //查询部门，岗位
            List<Map<String, Object>> listuser = finddepjob(map);
            String job_name = "", dep_name = "";
            for(Map<String,Object> map1 : listuser){
                if(map.get("UID").toString().contains(map1.get("id").toString())){
                    job_name += map1.get("job_name").toString() + ",";
                    dep_name += map1.get("dep_name").toString() + ",";
                }
            }
            map.put("job_name",job_name);
            map.put("dep_name",dep_name);
            list.add(map);
        }

        //计算下发时间，创建时间，结束时间
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar1 = Calendar.getInstance();
        calendar1.add(Calendar.DAY_OF_YEAR, 1);//明天
        Date futureDate1 = calendar1.getTime();
        String futureDateString = dateFormat1.format(futureDate1)+ " 08:00:00";
        String[] sql = new String[planList2.size()];
        int i =0;
        for(Map<String,Object> map : list){
            int pl = Integer.parseInt(map.get("HECK_CYCL").toString());
            Calendar calendar2 = Calendar.getInstance();
            calendar2.add(Calendar.DAY_OF_YEAR, 1);//明天
            if("天".equals(timeType)){
                calendar2.add(dateType, pl);
            }
            if("月".equals(timeType) ){
                calendar2.add(dateType, pl);
            }
            if("年".equals(timeType) ){
                calendar2.add(dateType, pl);
            }
            Date futureDate2 = calendar2.getTime();
            String futureDateString2 = dateFormat1.format(futureDate2)+ " 08:00:00";

            sql[i] = "insert into hd_check_task_new(RWID,PID,DNAME,PNAME,UNAME,USERID,INVESTIGATION_DATE,CREATE_DATE,endtime,IS_DEFEND) " +
                    " value (" +
                    " '"+ESN.getUUID()+"', " +
                    " '"+map.get("id")+"', " +
                    " '"+map.get("dep_name")+"', " +
                    " '"+map.get("job_name")+"', " +
                    " '"+map.get("UNAMELIST")+"', " +
                    " '"+map.get("UID")+"', " +
                    " '"+futureDateString+"', " +
                    " '"+futureDateString+"', " +
                    " '"+futureDateString2+"', " +
                    " '0'" +
                    ") ; ";
            i++ ;
        }
        jdbcTemplate.batchUpdate(sql);
    }
    public void setNewHourTakeToTable(List<Map<String,Object>> listnwetask){
        String[] sql = new String[listnwetask.size()];
        int i =0;
        for(Map<String,Object> map : listnwetask){
           sql[i] = "insert into hd_check_task_new(RWID,PID,DNAME,PNAME,UNAME,USERID,INVESTIGATION_DATE,CREATE_DATE,endtime,IS_DEFEND) " +
                    " value (" +
                    " '"+map.get("RWID")+"', " +
                    " '"+map.get("pid")+"', " +
                    " '"+map.get("dep_name")+"', " +
                    " '"+map.get("job_name")+"', " +
                    " '"+map.get("nickname")+"', " +
                    " '"+map.get("mpeopleids")+"', " +
                    " '"+map.get("startTime")+"', " +
                    " '"+map.get("startTime")+"', " +
                    " '"+map.get("endTime")+"', " +
                    " '0' " +
                    ") ; ";
           i++ ;
        }
        jdbcTemplate.batchUpdate(sql);

    }
    public void setHourTake(List<Map<String,Object>> ondutyList,List<Map<String,Object>> planList1)throws Exception{
        //小时任务整合
        List<Map<String, Object>> onlyusertask = new ArrayList<>();//单人次任务
        for(Map<String, Object> map : planList1){
            for(Map<String, Object> onduty : ondutyList){
                if(StringUtils.isEmpty(onduty.get("mpeopleid"))){
                    break;
                }else{
                    if(map.get("UID").toString().contains(onduty.get("mpeopleid").toString())){
                        Map<String, Object> map1 = new HashMap<>();
                        map1.put("mpeopleid",onduty.get("mpeopleid"));
                        map1.put("startTime",onduty.get("startTime"));
                        map1.put("endTime",onduty.get("endTime"));
                        map1.put("nickname",onduty.get("nickname"));
                        map1.put("job_name",onduty.get("job_name"));
                        map1.put("job_id",onduty.get("job_id"));
                        map1.put("dep_name",onduty.get("dep_name"));
                        map1.put("dep_id",onduty.get("dep_id"));
                        map1.put("id",map.get("id"));
                        map1.put("UNAMELIST",map.get("UNAMELIST"));
                        map1.put("UID",map.get("UID"));
                        map1.put("iftime",map.get("iftime"));
                        map1.put("UPDATE_DATE",map.get("UPDATE_DATE"));
                        map1.put("HECK_CYCL",map.get("HECK_CYCL"));
                        onlyusertask.add(map1);
                    }

                }

            }
        }
        //去重单人次任务
        List<Map<String, Object>> totalList = new ArrayList<>();
        for(Map<String, Object> map : planList1){
            List<Map<String, Object>> listnwe = new ArrayList<>();
            for(Map<String, Object> map1 : onlyusertask){
                if(map.get("id").equals(map1.get("id"))){
                    //9
                    listnwe.add(map1);
                }
            }
            if(listnwe.size()>0){
                List<Map<String, Object>> listnwegroup = new ArrayList<>();
                // 合并相同map项
                Map<Object,Map<String, Object>> xmap = new HashMap<>();
                for (Map<String, Object> map2 : listnwe) {
                    Map<String, Object> mergedMaps = new HashMap<>();
                    String names = map2.get("nickname").toString(),
                            mpeopleids = map2.get("mpeopleid").toString(),
                            startTime = map2.get("startTime").toString(),
                            endTime = map2.get("endTime").toString(),
                            job_name = map2.get("job_name").toString(),
                            dep_name  = map2.get("dep_name").toString(),
                            pid = map2.get("id").toString(),
                            HECK_CYCL = map2.get("HECK_CYCL").toString();
                    for(int i=1;i<listnwe.size();i++){
                        if(map2.get("startTime").equals(listnwe.get(i).get("startTime")) && map2.get("endTime").equals(listnwe.get(i).get("endTime"))
                                && !map2.get("nickname").equals(listnwe.get(i).get("nickname"))){
                            names = listnwe.get(i).get("nickname").toString()+","+names;
                            mpeopleids = listnwe.get(i).get("mpeopleid").toString()+","+mpeopleids;
                            job_name = listnwe.get(i).get("job_name").toString()+","+job_name;
                            dep_name = listnwe.get(i).get("dep_name").toString()+","+dep_name;

                        }
                    }
                    if(!xmap.containsKey(startTime+"|"+endTime)){
                        mergedMaps.put("nickname",names);
                        mergedMaps.put("mpeopleids",mpeopleids);
                        mergedMaps.put("startTime",startTime);
                        mergedMaps.put("endTime",endTime);
                        mergedMaps.put("pid",pid);
                        mergedMaps.put("dep_name",dep_name);
                        mergedMaps.put("job_name",job_name);
                        mergedMaps.put("HECK_CYCL",HECK_CYCL);
                        listnwegroup.add(mergedMaps);
                        xmap.put(startTime+"|"+endTime,mergedMaps);
                    }
                }
                totalList.addAll(listnwegroup);
            }
        }
        //下发数据格式 startTime=2024-09-13 08: 00: 00     endTime=2024-09-13 16: 00: 00
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH");
        Date date = new Date();
        String timestr = dateFormat1.format(date) + ":00:00";
        int HECK_CYCL = 0,shint=0,ehint=0;
        Long downnum ;
        String startT = "",endT = "",sh="",eh="",newhour="",newday="";
        List<Map<String, Object>> listnwetask = new ArrayList<>();
        for(Map<String, Object> map : totalList){
            HECK_CYCL = Integer.parseInt(map.get("HECK_CYCL").toString());
            startT = map.get("startTime").toString();
            sh = startT.substring(11,13);
            shint = Integer.parseInt(sh);
            endT = map.get("endTime").toString();
            eh = endT.substring(11,13);
            ehint = Integer.parseInt(eh)==0?24:Integer.parseInt(eh);
            Date date1 = dateFormat.parse(startT);
            Date date2 = dateFormat.parse(endT);
            Date date3 = dateFormat.parse(timestr);
            long timestamp1 = date1.getTime();
            long timestamp2 = date2.getTime();
            long timestamp3 = date3.getTime();
            downnum =  ((timestamp2 - timestamp1) / 1000 / 60 / 60 / HECK_CYCL);

            for(int i=0;i<downnum;i++){
                newhour = ((i*HECK_CYCL+shint)+"").length()==1?"0"+(i*HECK_CYCL+shint):(i*HECK_CYCL+shint)+"";
                newday = startT.substring(0,10) + " " + newhour + ":00:00";
                Map<String, Object> map1 = new HashMap<>();
                map1.put("nickname",map.get("nickname"));
                map1.put("mpeopleids",map.get("mpeopleids"));
                map1.put("startTime",map.get("startTime"));
                map1.put("endTime",map.get("endTime"));
                map1.put("pid",map.get("pid"));
                map1.put("dep_name",map.get("dep_name"));
                map1.put("job_name",map.get("job_name"));
                map1.put("HECK_CYCL",map.get("HECK_CYCL"));
                map1.put("startTime",newday);
                map1.put("RWID", ESN.getUUID());
                listnwetask.add(map1);
            }
        }
        //存缓存或入新表
        System.out.println(listnwetask.size());
        setNewHourTakeToTable(listnwetask);
    }



//    @Scheduled(cron = "0 0 * * *  ?")
//    @PostConstruct
    public void gettaskHour(){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH");
        Date date = new Date();
        String time = dateFormat.format(date)+":00:00";
        String slql = "SELECT * FROM hd_check_task_new WHERE CREATE_DATE = '"+time+"'";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(slql);
        if(list.size() > 0){
            String[] sql = new String[list.size()];
            String[] sql2 = new String[list.size()];
            int i =0;
            int k =0;
            List<String> liststr = new ArrayList<>();
            for(Map<String,Object> map : list){
                sql[i] = "insert into hd_check_task(RWID,PID,DNAME,PNAME,UNAME,USERID,INVESTIGATION_DATE,CREATE_DATE,endtime,IS_DEFEND) " +
                        " value (" +
                        " '"+map.get("RWID")+"', " +
                        " '"+map.get("PID")+"', " +
                        " '"+map.get("DNAME")+"', " +
                        " '"+map.get("PNAME")+"', " +
                        " '"+map.get("UNAME")+"', " +
                        " '"+map.get("USERID")+"', " +
                        " '"+map.get("INVESTIGATION_DATE")+"', " +
                        " '"+map.get("CREATE_DATE")+"', " +
                        " '"+map.get("endtime")+"', " +
                        " '"+map.get("IS_DEFEND")+"' " +
                        ") ; ";
                sql2[i] = "update hd_check_plain set UPDATE_DATE = '"+time+"' where ID = '"+map.get("PID")+"'";

                String userid[] = map.get("USERID").toString().split(",");
                String str = "",str2="";
                for(String user : userid){
                    String mes_id = ESN.getUUID();
                    str = "INSERT INTO sys_message (message_id,message_title,message_content,message_sender,message_senderid,create_time, " +
                            " update_time,message_status ) " +
                            " VALUE ( '" + mes_id + "', " +
                            " '隐患排查任务推送', " +
                            " '您有一条新的隐患排查任务推送', " +
                            " '系统', " +
                            " '733914f8-3435-4e35-b02e-d51fbc1b5cc1', " +
                            " now(), " +
                            " now(), " +
                            " '1' " +
                            " ) ";
                    str2 = "INSERT INTO sys_user_message (id,user_id,message_id,isread) " +
                            " VALUE ( '" + ESN.getUUID() + "', " +
                            " '"+ user +"', " +
                            " '" + mes_id + "', " +
                            " '0' " +
                            " ) ";
                    liststr.add(str);
                    liststr.add(str2);
                }
                i++ ;
            }
            String[] sql3 = liststr.toArray(new String[liststr.size()]);
            jdbcTemplate.batchUpdate(sql);
            jdbcTemplate.batchUpdate(sql2);
            jdbcTemplate.batchUpdate(sql3);
        }
    }




    public static boolean isBetween(LocalDateTime beginTime, LocalDateTime endTime) {
        LocalDateTime now = LocalDateTime.now();
        boolean flag = false;
        if (now.isAfter(beginTime) && now.isBefore(endTime)) {
            flag = true;
        }
        return flag;
    }




}
